package fr.azzale.casu.activity;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import fr.azzale.casu.R;
import fr.azzale.casu.TribuneApplication;
import fr.azzale.casu.metier.Casu;
import fr.azzale.casu.utils.AuthCasuWebViewClient;
import fr.azzale.casu.utils.Utils;

public class AuthActivity extends Activity {

	public class LoadCasuTask extends AsyncTask<Void, Void, String> {

		@Override
		protected void onPreExecute() {
			findViewById(R.id.pb).setVisibility(View.VISIBLE);
		}

		@Override
		protected String doInBackground(Void... params) {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			BasicCookieStore cookieStore = new BasicCookieStore();
			httpclient.setCookieStore(cookieStore);

			HttpGet request = new HttpGet(Utils.URLLOGIN);
			int status = 0;
			byte[] result = null;
			try {
				HttpResponse http_response = httpclient.execute(request);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				InputStream content = http_response.getEntity().getContent();
				if (content == null)
					Log.e("erreur android", "null");
				else {
					BufferedReader br = new BufferedReader(
							new InputStreamReader(content));
					FileOutputStream fos = openFileOutput("login.html",
							Context.MODE_PRIVATE);
					String line = "";
					while ((line = br.readLine()) != null) {
						byte[] bytes = line.getBytes();
						fos.write(bytes);
						baos.write(bytes);
					}
					fos.flush();
					fos.close();
					result = baos.toByteArray();
					baos.close();
				}
			} catch (Exception e) {

			}
			// webview.loadDataWithBaseURL(Utils.URLLOGIN,
			// Utils.readAuthPage(this), "", "UTF-8", "");
			HashMap<String, Casu> casus = (HashMap<String, Casu>) Utils.deserializeObject(AuthActivity.this, "casus");
			if (casus == null)
				casus = new HashMap<String, Casu>();
			((TribuneApplication) getApplication()).setCasus(casus);
			try {
				String html = new String(result, "UTF-8");
				int sessionidStart = html.indexOf("hashLoginPassword(this, '")+"hashLoginPassword(this, '".length();
				if(sessionidStart>0)
				{
					getSharedPreferences("Casu", Context.MODE_PRIVATE).edit().putString("sessionid", html.substring(sessionidStart, html.indexOf("'", sessionidStart+1))).commit();
				}
				return html;
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			findViewById(R.id.pb).setVisibility(View.GONE);
			webview.addJavascriptInterface(new MyJavaScriptInterface(),
					"HTMLOUT");
			AuthCasuWebViewClient wvc = new AuthCasuWebViewClient(
					AuthActivity.this);
			webview.setWebViewClient(wvc);
			webview.loadDataWithBaseURL(Utils.URLLOGIN, result, "text/html", "UTF-8", "");
		}

	}

	private WebView webview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.auth);
		webview = (WebView) findViewById(R.id.authWV);

		new LoadCasuTask().execute(new Void[] {});

	}

	class MyJavaScriptInterface {
		public void showHTML(String html) {
			Log.d("html", "" + html);
		}
	}

}
